import request from '@/services/http'
import _ from 'lodash'

export default class Nls {
  wss_url = 'wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1?token='
  token_url = '/euc/auth/getAliToken'

  appKey = 'OLhmNQFe8qAxwmLj'

  callbacks = []

  socket = null

  canSendBinary = false

  constructor() {
    this.getToken()
      .then((token) => {
        this.socket = new WebSocket(this.wss_url + token)
        console.log('token', token)

        this.task_id = this.randomMessageId()

        this.socket.onopen = () => {
          console.log('连接已建立')
          this.StartTranscription()
        }

        this.socket.onmessage = (event) => {
          console.log('收到消息:', event.data)
          const json = JSON.parse(event.data)
          const eventName = _.get(json, 'header.name')
          if (eventName === 'TranscriptionStarted') {
            this.canSendBinary = true
          }
          if (eventName === 'SentenceEnd') {
            const result = _.get(json, 'payload.result')
            this.emit(result)
          }
        }
      })
      .catch((err) => {
        console.log(err)
        this.emit('获取nls token失败')
      })
  }

  randomMessageId() {
    // 定义字符池（包含数字、大小写字母）
    const chars = '0123456789abcdef'
    return _.times(32, () => {
      const index = _.random(0, chars.length - 1) // 随机选取字符池索引
      return chars.charAt(index)
    }).join('')
  }

  on(callback) {
    if (_.isFunction(callback)) {
      this.callbacks.push(callback)
    }
  }

  emit(data) {
    _.each(this.callbacks, (fn) => fn(data))
  }

  getToken() {
    return request({
      url: this.token_url,
      method: 'get',
    }).then((res) => {
      console.log('getToken', res)
      return _.get(res, 'data.token')
    })
  }

  StartTranscription() {
    this.socket.send(
      JSON.stringify({
        header: {
          message_id: this.randomMessageId(),
          task_id: this.task_id,
          namespace: 'SpeechTranscriber',
          name: 'StartTranscription',
          appkey: this.appKey,
        },
        payload: {
          format: 'PCM',
          sample_rate: 16000,
          enable_intermediate_result: true,
          enable_punctuation_prediction: true,
          enable_inverse_text_normalization: true,
        },
      }),
    )
  }

  StopTranscription() {
    this.socket.send(
      JSON.stringify({
        header: {
          message_id: this.randomMessageId(),
          task_id: this.task_id,
          namespace: 'SpeechTranscriber',
          name: 'StopTranscription',
          appkey: this.appKey,
        },
      }),
    )
  }

  send(data) {
    // this.emit(data)
    if (this.canSendBinary) {
      this.socket.send(data)
    }
  }

  close() {
    if (this.socket) {
      this.StopTranscription()
      setTimeout(() => {
        this.socket.close()
        this.socket = null
      }, 2000)
    }
  }
}
